﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using LanDBom.Models;
using LanDBom.Models.Algorithm;
using System.Dynamic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using System.Threading;
using System.Windows.Forms;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using Newtonsoft.Json.Linq;
using System.Text;
using Microsoft.Ajax.Utilities;
using System.Web.Helpers;
using Org.BouncyCastle.Asn1.Crmf;
using System.Security.Policy;
using Microsoft.Office.Interop.Excel;
using System.Data;
using NPOI.OpenXmlFormats.Dml;
using System.Reflection;

namespace LanDBom.Controllers
{
    public class DetailedController : Controller
    {
        private LDbaseEntities db = new LDbaseEntities();
        GY_Algorithm GY = new GY_Algorithm();
        Find_ShoTJ tJ = new Find_ShoTJ();
        // GET: Detailed
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Boms(string names, string bina = "", string binaed = "", string hudnf = "", int state = 0, string SFJR = "")
        {
            if (names == null)
            {
                names = "-1";
            }
            if (state == 1)
            {
                List<BOMini> bOMinis = db.BOMini.Where(s => s.BOM2_bian == bina).ToList();
                var list = from a in bOMinis select new { a.BOM2_chen, a.BOM2_Nian, a.BOM2_liao, a.BOM2_duan, a.BOM2_bian, a.BOM2_wuLiu, a.BOM2_Yong, a.BOM2_sunhao, a.BOM2_Lei, a.BOM2_Ctime, a.BOM2_mioa, a.BOM2_Guige };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 3)
            {
                var spp = db.Applications.FirstOrDefault(s => s.AP_bian == hudnf);
                List<BOMini> bOMinis = db.BOMini.Include("Formation").Where(s => s.BOM2_bian == hudnf && s.BOM2_BQing.Contains(binaed) && s.BOM2_Zhuang == spp.App_BanB).ToList();
                var list = from a in bOMinis select new { a.BOM2_chen, a.BOM2_Nian, a.BOM2_liao, a.BOM2_duan, a.BOM2_bian, a.BOM2_wuLiu, a.BOM2_Yong, a.BOM2_sunhao, a.BOM2_Lei, a.BOM2_Ctime, a.BOM2_mioa, a.BOM2_Guige, a.BOM2_Sone, a.BOM2_ST, a.BOM2_fenzi, a.BOM2_id, a.Fo_id, beih = a.Formation == null ? "" : a.Formation.FM_ms };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 4)
            {
                Applications app = db.Applications.Where(a => a.AP_bian == binaed).FirstOrDefault();

                app.App_bu = SFJR;
                db.Entry(app).State = EntityState.Modified;
                int row = db.SaveChanges();
                string messsage = row > 0 ? "1" : "0";
                return Content(messsage, "application/json");
            }
            //names = "SQ202311136225661";
            var applications = db.Applications.Where(s => s.AP_bian == names).ToList();
            var snif = db.Applications.Where(r => r.AP_bian == names).FirstOrDefault();
            var hdns = snif.App_BanB;
            List<BOMini> bOMins = db.BOMini.Where(s => s.BOM2_bian == names && s.BOM2_chen == "Leve0" && s.BOM2_Zhuang == hdns).ToList();
            var shnf = db.JiCheng.FirstOrDefault(s => s.JC_bianhao == names && s.JC_zhuang != "已删除");
            ViewBag.fhishf = bOMins;
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.OrderBy(s => s.Je_hanghao).ToList();
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.temp2 = db.buty3.ToList();
            Session["JC_zhuang"] = shnf == null ? null : shnf.JC_zhuang;
            return View(applications);
        }
        public ActionResult BoomS(string Bian = "", int state = 0)
        {
            if (state == 1)
            {
                var bomn = db.Applications.FirstOrDefault(s => s.AP_bian == Bian);
                var bana = bomn.App_BanB;
                var Bom = db.BOMini.Where(w => w.BOM2_bian == Bian && w.BOM2_Zhuang == bana && w.BOM2_Lei != "自制").ToList();
                var dt = new System.Data.DataTable();
                dt.Columns.Add("csdr", typeof(string));
                foreach (var item in Bom)
                {
                    var shu = item.BOM2_ST;
                    shu = shu == "缓冲材" ? "泡沫（裁切/粘合）" : shu;//临时
                    var durn = db.duty.Where(f => f.du_name == shu).FirstOrDefault();
                    var Ijd = durn.dl_id;
                    var denn = db.Dengli.Find(Ijd).DE_nae;
                    DataRow[] infu = dt.Select("csdr = '" + denn + "'");
                    if (infu.Length == 0)
                    {
                        dt.Rows.Add(denn);
                    }
                    else
                    {
                        continue;
                    }
                }
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(dt, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 2)
            {
                Applications app = db.Applications.Where(a => a.AP_bian == Bian).FirstOrDefault();
                var Booming = db.BOMini.Where(s => s.BOM2_bian == Bian && s.BOM2_Zhuang == app.App_BanB).ToList();
                int jil = 0;
                foreach (var b in Booming)
                {
                    var liao = b.BOM2_liao;
                    var N1 = db.Ndardo.Where(s => s.Fo_id == liao).FirstOrDefault();
                    if (N1 == null)
                    {
                        jil++;
                    }
                }
                var messsage = jil > 0 ? "X" : "J";
                return Content(messsage);
            }
            if (state == 3)
            {
                var appp = db.Applications.Where(s => s.AP_bian == Bian).FirstOrDefault();
                var bomin = db.BOMini.Where(l => l.BOM2_bian == Bian && l.BOM2_Zhuang == appp.App_BanB).ToList();
                int shu = 0;
                int sum = 0;
                foreach (var b in bomin)
                {
                    var liao = b.BOM2_liao;
                    var N1 = db.Ndardo.Where(s => s.Fo_id == liao).FirstOrDefault();
                    if (N1 != null)
                    {
                        sum++;
                        b.BOM2_CB = N1.Nd_danwei;
                    }
                    db.Entry(b).State = EntityState.Modified;
                    shu += db.SaveChanges();
                }
                var messsage = shu == sum ? "1" : "2";
                return Content(messsage);
            }
            return View();
        }
        public ActionResult BOMView(string names)
        {
            if (names == null)
            {
                names = "-1";
            }
            List<Applications> applications = db.Applications.Where(s => s.AP_bian == names).ToList();
            List<BOMini> bOMinis = db.BOMini.Include(s => s.Formation).Where(s => s.BOM2_bian == names).OrderBy(s => s.BOM2_BQing).ToList();
            ViewBag.fgh = bOMinis;
            ViewBag.appji = applications;
            return View();
        }
        //报价页面
        public ActionResult BomsView(string names, int state = 0, string BOM_Gong = "")
        {
            //names = "SQ202311136225661";
            if (names == null)
            {
                names = "-1";
            }
            var app = db.Applications.Where(a => a.AP_bian == names).FirstOrDefault();
            var shun = new List<Applications>();
            shun.Add(app);
            List<BOMini> bOs = new List<BOMini>();
            if (app.App_BanB == null)
            {
                bOs = db.BOMini.Where(a => a.BOM2_bian == names).OrderBy(s => s.BOM2_BQing).ToList();
            }
            else
            {
                bOs = db.BOMini.Where(a => a.BOM2_bian == names && a.BOM2_Zhuang == app.App_BanB).OrderBy(s => s.BOM2_BQing).ToList();
            }
            List<Formation> fo = db.Formation.ToList();
            List<Ndardo> nd = db.Ndardo.ToList();
            ViewBag.ListAPP = shun;
            //计算总价
            double T_price = 0;
            if (state == 1)
            {
                //T_price = GY.Tprice(bOs);
                /*var lists = from a in bOs
                            join d in nd on a.BOM2_liao equals d.Fo_id into jtenm
                            from fgh in jtenm.DefaultIfEmpty()
                            select new { a.BOM2_Gong, a.BOM2_id, a.BOM2_chen, a.BOM2_wuLiu, a.BOM2_liao, a.BOM2_duan, a.BOM2_Nian, a.BOM2_Yong, a.BOM2_mioa, Nd_Gong = fgh == null ? "未询价" : fgh.Nd_Gong, Nd_jiage = fgh == null ? 0 : fgh.Nd_jiage, Nd_danwei = fgh == null ? "N" : fgh.Nd_danwei };*/
                //BOM拆分
                var BOMs = new List<BOMini>();
                foreach (var item in bOs)
                {
                    var shu = item.BOM2_CB.Split(',');
                    var s = item.BOM2_mioa;//添加利润结果
                    var sfhu = item.BOM2_Jin;//添加的利润
                    for (int i = 0; i < shu.Length; i++)
                    {
                        if (shu[i] != null && shu[i] != "")
                        {
                            var K = shu[i].Split(':');//供应商ID：阶梯：成本
                            var ID = int.Parse(K[0]);
                            var GONG = db.Informa.FirstOrDefault(w => w.Inf_id == ID);
                            var M = MIoa(s, K[1]);
                            var L = MIoa(sfhu, K[1]);
                            BOMini JKM = KLMKOO(item, K, GONG, M, L);
                            BOMs.Add(JKM);
                        }
                    }
                }

                var LIstn = from a in BOMs
                            select new
                            {
                                a.BOM2_Gong,
                                a.BOM2_id,
                                a.BOM2_chen,
                                a.BOM2_wuLiu,
                                a.BOM2_duan,
                                a.BOM2_Nian,
                                a.BOM2_Yong,
                                a.BOM2_mioa,
                                Nd_Gong = a.BOM2_sdname,
                                Nd_jiage = a.BOM2_CB,
                                a.BOM2_fenzi,
                                a.BOM2_sd,
                                a.BOM2_Jin,
                                a.BOM2_liao,
                            };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(LIstn, settings);
                Session["T_pricesed"] = T_price;
                return Content(jsongStr, "application/json");
            }

            //显示工艺功能
            if (state == 2)
            {
                int shu = -1;
                if (BOM_Gong != "" && BOM_Gong != "null" && BOM_Gong != null)
                {
                    shu = int.Parse(BOM_Gong);
                }
                List<operational> ope = db.operational.Where(a => a.OP_ID == shu).ToList();
                var lists = from a in ope select new { a.OP_ID, a.OP_Yin, a.OP_YinSe, a.OP_Muqie, a.OP_Muxinag, a.OP_biao, a.OP_Mujiu, a.OP_TIgong, a.OP_Wuli, a.OP_price };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(lists, settings);

                return Content(jsongStr, "application/json");
            }
            if (state == 4)
            {
                try
                {
                    var Shenqin = db.Applications.FirstOrDefault(s => s.AP_bian == names);
                    var BOMIN = db.BOMini.Where(s => s.BOM2_bian == names && s.BOM2_Zhuang == Shenqin.App_BanB).ToList();
                    //计算集成
                    //
                    //集成查询客户
                    var client = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Info = new StringBuilder();
                    //业务对象标识
                    string formId = "SAL_QUOTATION";
                    string cs = "{\r\n    \"NeedUpDateFields\": [],\r\n    \"NeedReturnFields\": [],\r\n    \"IsDeleteEntry\": \"true\",\r\n    \"SubSystemId\": \"\",\r\n    \"IsVerifyBaseDataField\": \"false\",\r\n    \"IsEntryBatchFill\": \"true\",\r\n    \"ValidateFlag\": \"true\",\r\n    \"NumberSearch\": \"true\",\r\n    \"IsAutoAdjustField\": \"false\",\r\n    \"InterationFlags\": \"\",\r\n    \"IgnoreInterationFlag\": \"\",\r\n    \"IsControlPrecision\": \"false\",\r\n    \"ValidateRepeatJson\": \"false\",\r\n    \"Model\": {\r\n        \"FID\": 0,\"FBillTypeID\": {\"FNUMBER\": \"XSBJD01_SYS\"},\"FDate\": \"" + Shenqin.App_qishi + "\",\"FCUSTID\": { \"FNUMBER\": \"" + Shenqin.App_miao + "\"},\"FCustLocId\": {\"FNumber\": \"" + Shenqin.App_miao + "\"},\"FSaleOrgId\": {\"FNumber\": \"10.01\"},\"FSaleDeptId\": {\"FNumber\": \"\"},\"FSaleGroupId\": {\"FNumber\": \"\"},\"FSalerId\": {\"FNumber\": \"\"},\"FEFFECTIVEDATE\": \"" + Shenqin.App_qishi + "\",\"FExpiryDate\": \"" + Shenqin.App_JTime + "\",\"FOPPID\": 0,\"FSettleId\": {\"FNUMBER\": \"" + Shenqin.App_qishi + "\"},\"FQUOTATIONFIN\": {\"FIsPriceExcludeTax\": true,\"FIsIncludedTax\": true,\"FSettleCurrId\": {\"FNumber\": \"PRE001\"},\"FRecConditionId\": {\"FNumber\": \"YJ90\"},\"FLocalCurrId\": {\"FNumber\": \"PRE001\"},\"FExchangeTypeId\": {\"FNumber\": \"HLTX01_SYS\"},\"FExchangeRate\": 1.0},";
                    //添加BOM
                    cs += "\"FQUOTATIONENTRY\":[";
                    BOMIN = BOMIN.Where(s => s.BOM2_chen == "Leve0").ToList(); var sjifn = 0;
                    var HUNF = "";
                    var JInkm = 0;
                    foreach (var item in BOMIN)
                    {
                        JInkm++;
                        var liao = WLShangc1(item.BOM2_id);
                        var OP = db.operational.Where(s => s.OP_ID == item.BOM2_Gong).FirstOrDefault();//物料成本
                        var EDF = item.BOM2_mioa == "" ? OP.OP_price.ToString() : item.BOM2_mioa;//进行赋值
                        var shund = db.Freht.Where(s => s.Fre_beizhu == item.BOM2_fenzi).FirstOrDefault();
                        var danhu = shund == null ? "Pcs" : shund.Fre_shijian;
                        var HHSN = EDF.Split(',');
                        for (int i = 0; i < HHSN.Length; i++)
                        {
                            if (HHSN[i] == "")
                            {
                                continue;
                            }
                            var HH = HHSN[i].Split(':');//阶梯 +价格
                            var price = 0.0;
                            var jieti = 1;
                            if (HH.Length == 2)
                            {
                                price = double.Parse(HH[1]);
                                jieti = int.Parse(HH[0].ToString());
                            }
                            else
                            {
                                var P = HH[0] == "" ? "0" : HH[0].ToString();
                                price = double.Parse(P);
                            }
                            HUNF += "{\r\n                \"FRowType\": \"Standard\",\r\n                \"FMaterialId\": {\r\n                    \"FNumber\": \"" + liao + "\"\r\n                },\r\n                \"FMaterialName\": \"" + item.BOM2_wuLiu + "\",\r\n                \"FUnitID\": {\r\n                    \"FNumber\": \"" + danhu + "\"\r\n                },\r\n                \"FInventoryQty\": 0.0,\r\n                \"FQty\": " + jieti + ",\r\n                \"FPrice\":0.0,\r\n                \"FTaxPrice\":" + (price * 1.13) + ",\r\n                \"FIsFree\": false,\r\n                \"FTaxRate\": 13.00,\r\n                \"FStartQty\":" + jieti + ",\r\n                \"FPriceCoefficient\": 1.0,\r\n                \"FPriceDiscount\": 0.0,\r\n                \"FDiscountRate\": 0.0,\r\n                \"FPriceBaseQty\": " + jieti + ",\r\n                \"FSetPriceUnitID\": {\r\n                    \"FNumber\": \"" + danhu + "\"\r\n                },\r\n                \"FStockUnitID\": {\r\n                    \"FNumber\": \""+ danhu + "\"\r\n                },\r\n          \"FStockQty\":" + jieti + ",\r\n                \"FStockBaseQty\": " + jieti + ",\r\n                \"FChangeFlag\": \"0\",\r\n                \"FBOMEntryId\": 0\r\n            }";
                            //物料为最后一个 阶梯为最大

                            if (BOMIN.Count() == JInkm)
                            {
                                if (i != HHSN.Length - 1)
                                {
                                    HUNF += ",";
                                }
                            }
                            else
                            {
                                HUNF += ",";
                            }
                        }
                    }
                    cs = cs + HUNF + "]}}";
                    //调用接口
                    var resultJson = client.Save(formId, cs);
                    //对返回结果进行解析和校验，这里使用的是JsonPatch
                    var resultJObject = JObject.Parse(resultJson);
                    var queryNode = resultJObject.SelectToken("$..IsSuccess");
                    var BONID = resultJObject.SelectToken("$.Result.Id");
                    var BONNmuber = resultJObject.SelectToken("$.Result.Number");
                    var CuoWu = resultJObject.SelectTokens("$..Message");
                    var jsongStr = "";
                    //判断并记录结果
                    bool isSucc = false;
                    if (queryNode == null)
                    {
                        Info.AppendLine("返回异常");
                        jsongStr = "提交失败";
                    }
                    else
                    {
                        var isSuccess = queryNode.Value<Boolean>();
                        if (isSuccess)
                        {
                            //提交
                            //读取配置，初始化SDK
                            K3CloudApi clients = new K3CloudApi();
                            //用于记录结果
                            StringBuilder Infoed = new StringBuilder();
                            //业务对象标识
                            string formIdse = "SAL_QUOTATION";
                            //请求参数，要求为json字符串
                            string jsonDataws = "{\"CreateOrgId\":0,\"Numbers\":\"" + BONNmuber + "\",\"Ids\":\"" + BONID + "\",\"SelectedPostId\":0,\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                            //调用接口
                            var resultJsonsw = client.Submit(formIdse, jsonDataws);
                            //对返回结果进行解析和校验，这里使用的是JsonPatch
                            var resultJObjectss = JObject.Parse(resultJsonsw);
                            var queryNodes = resultJObjectss.SelectToken("$..IsSuccess");
                            //判断并记录结果
                            if (queryNodes == null)
                            {
                                Infoed.AppendLine("返回异常");
                            }
                            else
                            {
                                isSucc = queryNode.Value<Boolean>();
                                Infoed.AppendLine(isSucc ? "操作成功" : "操作失败");
                            }
                        }
                        Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        if (isSucc)
                        {
                            jsongStr = "提交成功";
                            //保存到数据库
                            var shunfn = (string)BONID;
                            var shufn = db.JiCheng.Where(s => s.JC_bianma == shunfn).Count();
                            if (shufn > 0)
                            {
                                var hisjne = db.JiCheng.FirstOrDefault(s => s.JC_bianma == BONID.ToString());
                                hisjne.JC_bianma = (string)BONID;
                                hisjne.JC_bianhao = (string)BONNmuber;
                                hisjne.JC_shen = Shenqin.App_qishi;
                                hisjne.JC_shi = Shenqin.App_JTime;
                                hisjne.JC_Yuan = names;
                                hisjne.JC_zhuang = "审批中";
                                hisjne.JC_ung = "正在审批";
                                db.Entry(hisjne).State = EntityState.Modified;
                            }
                            else
                            {
                                JiCheng ji = new JiCheng()
                                {
                                    JC_bianma = (string)BONID,
                                    JC_bianhao = (string)BONNmuber,
                                    JC_shen = Shenqin.App_qishi,
                                    JC_shi = Shenqin.App_JTime,
                                    JC_Yuan = names,
                                    JC_zhuang = "审批中",
                                };
                                db.JiCheng.Add(ji);
                            }
                            int shhnf = db.SaveChanges();
                            if (shhnf > 0)
                            {
                                Shenqin.App_bu = "8";
                                db.Entry(Shenqin).State = EntityState.Modified;
                                int sjimop = db.SaveChanges();
                                jsongStr += "审批中,编码：" + BONID + "";
                            }
                        }
                        else
                        {
                            jsongStr = "提交失败";
                        }
                    }
                    return Content(jsongStr);
                }
                catch (Exception ex)
                {
                    string shdunngf = ex.Message;
                    return Json(shdunngf);
                }
            }
            return View();
        }

        private static BOMini KLMKOO(BOMini item, string[] K, Informa GONG, string M, string L)
        {
            return new BOMini()
            {
                BOM2_Gong = item.BOM2_Gong,
                BOM2_id = item.BOM2_id,
                BOM2_chen = item.BOM2_chen,
                BOM2_wuLiu = item.BOM2_wuLiu,
                BOM2_duan = item.BOM2_duan,
                BOM2_Nian = item.BOM2_Nian,
                BOM2_Yong = item.BOM2_Yong,
                BOM2_fenzi = item.BOM2_fenzi,
                BOM2_liao = item.BOM2_liao,
                BOM2_sdname = GONG == null ? "" : GONG.Inf_gong,
                BOM2_mioa = M,
                BOM2_Jin = L,
                BOM2_CB = K[2],
                BOM2_sd = K[1],
                BOM2_bian = item.BOM2_bian,
            };
        }
        //上传物料  上传信息：物料名 分组 类型   bomid
        public string WLShangc1(int id)
        {
            var strj = "";
            var bom = db.BOMini.FirstOrDefault(s=>s.BOM2_id==id);
            if (bom != null)
            {
                //检测是佛存在
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_MATERIAL";
                string fieldKeys = "FNumber,FName,FSpecification,FErpClsID,FBaseUnitId.FNumber,FRefCost";//名称 编码 规格 采购属性 单位 价格
                string Filter = "FNumber like'" + bom.BOM2_liao + "%'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 20,
                };
                //调用接口
                var BOMC = client.ExecuteBillQuery(param.ToJson());
                if (BOMC.Count == 1)
                {
                    strj = bom.BOM2_liao;
                }
                else
                {
                    var ERj = bom.BOM2_ST;
                    var sh = db.buty2.Where(s => s.zl_name == ERj).FirstOrDefault();
                    var shu = "12.17.12";
                    if (sh != null)
                    {
                        shu = sh.ERP_Bm == null ? sh.ERP_Bm : sh.ERP_id;
                    }
                    var Danw = bom.BOM2_fenzi == null ? "Pcs" : bom.BOM2_fenzi;
                    var shund = db.Freht.Where(s => s.Fre_beizhu == Danw).FirstOrDefault();
                    var danhu = shund == null ? "Pcs" : shund.Fre_shijian;
                    //用于记录结果
                    //业务对象标识
                    //
                    string cs = "{\r\n    \"NeedUpDateFields\": [],\r\n    \"NeedReturnFields\": [],\r\n    \"IsDeleteEntry\": \"true\",\r\n    \"SubSystemId\": \"\",\r\n    \"IsVerifyBaseDataField\": \"false\",\r\n    \"IsEntryBatchFill\": \"true\",\r\n    \"ValidateFlag\": \"true\",\r\n    \"NumberSearch\": \"true\",\r\n    \"IsAutoAdjustField\": \"true\",\r\n    \"InterationFlags\": \"\",\r\n    \"IgnoreInterationFlag\": \"\",\r\n    \"IsControlPrecision\": \"false\",\r\n    \"ValidateRepeatJson\": \"false\",\r\n\"IsAutoSubmitAndAudit\":true,    \"Model\": {\r\n        \"FMATERIALID\": 0,\r\n        \"FCreateOrgId\": {\r\n            \"FNumber\": \"10.01\"\r\n        },\r\n        \"FUseOrgId\": {\r\n            \"FNumber\": \"10.01\"\r\n        },\r\n\t\"FNumber\": \"" + bom.BOM2_liao + "\",\r\n        \"FName\": \"" + bom.BOM2_wuLiu + "\",\r\n \r\n        \"FSpecification\": \""+bom.BOM2_Guige+"\",       \"FMaterialGroup\": {\r\n            \"FNumber\": \"" + shu + "\"\r\n        },\r\n\t\"FDescription\":\"报价系统上传物料\",\r\n        \"FDSMatchByLot\": false,\r\n        \"FImgStorageType\": \"B\",\r\n        \"FIsSalseByNet\": false,\r\n        \"FIsHandleReserve\": true,\r\n        \"SubHeadEntity\": {\r\n            \"FErpClsID\": \"1\",\r\n            \"FFeatureItem\": \"1\",\r\n            \"FCategoryID\": {\r\n                \"FNumber\": \"CHLB01_SYS\"\r\n            },\r\n            \"FTaxType\": {\r\n                \"FNumber\": \"WLDSFL01_SYS\"\r\n            },\r\n            \"FTaxRateId\": {\r\n                \"FNUMBER\": \"SL02_SYS\"\r\n            },\r\n            \"FBaseUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FWEIGHTUNITID\": {\r\n                \"FNUMBER\": \"kg\"\r\n            },\r\n            \"FVOLUMEUNITID\": {\r\n                \"FNUMBER\": \"m\"\r\n            },\r\n            \"FSuite\": \"0\"\r\n        },\r\n        \"SubHeadEntity1\": {\r\n            \"FStoreUnitID\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FUnitConvertDir\": \"1\",\r\n            \"FCurrencyId\": {\r\n                \"FNumber\": \"PRE001\"\r\n            },\r\n            \"FSNManageType\": \"1\",\r\n            \"FSNGenerateTime\": \"1\"\r\n        },\r\n        \"SubHeadEntity2\": {\r\n            \"FSaleUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FSalePriceUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FWARRANTYUNITID\": \"D\",\r\n            \"FOutLmtUnit\": \"SAL\",\r\n            \"FTaxDiscountsType\": \"0\"\r\n        },\r\n        \"SubHeadEntity3\": {\r\n            \"FBaseMinSplitQty\": 0.0,\r\n            \"FPurchaseUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FPurchasePriceUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FQuotaType\": \"1\",\r\n            \"FPOBillTypeId\": {\r\n                \"FNUMBER\": \"CGSQD01_SYS\"\r\n            },\r\n            \"FIsEnableScheduleSub\": false\r\n        },\r\n        \"SubHeadEntity4\": {\r\n            \"FPlanMode\": \"0\",\r\n            \"FBaseVarLeadTimeLotSize\": 0.0,\r\n            \"FPlanningStrategy\": \"1\",\r\n            \"FMfgPolicyId\": {\r\n                \"FNumber\": \"ZZCL001_SYS\"\r\n            },\r\n            \"FOrderPolicy\": \"0\",\r\n            \"FFixLeadTimeType\": \"1\",\r\n            \"FVarLeadTimeType\": \"1\",\r\n            \"FCheckLeadTimeType\": \"1\",\r\n            \"FOrderIntervalTimeType\": \"3\",\r\n            \"FMaxPOQty\": 100000.0,\r\n            \"FEOQ\": 1.0,\r\n            \"FReserveType\": \"1\",\r\n            \"FPlanOffsetTimeType\": \"1\"\r\n        },\r\n        \"SubHeadEntity5\": {\r\n            \"FProduceUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FFinishReceiptOverRate\": 200.0,\r\n            \"FFinishReceiptShortRate\": 0.0,\r\n            \"FProduceBillType\": {\r\n                \"FNUMBER\": \"SCDD05_SYS\"\r\n            },\r\n            \"FOrgTrustBillType\": {\r\n                \"FNUMBER\": \"SCDD06_SYS\"\r\n            },\r\n            \"FIsProductLine\": false,\r\n            \"FIsSNCarryToParent\": false,\r\n            \"FBOMUnitId\": {\r\n                \"FNumber\": \"" + danhu + "\"\r\n            },\r\n            \"FIssueType\": \"1\",\r\n            \"FOverControlMode\": \"2\",\r\n            \"FMinIssueUnitId\": {\r\n                \"FNUMBER\": \"" + danhu + "\"\r\n            },\r\n            \"FStandHourUnitId\": \"3600\",\r\n            \"FBackFlushType\": \"1\"\r\n        },\r\n        \"SubHeadEntity6\": {\r\n            \"FFirstQCControlType\": \"0\"\r\n        },\r\n        \"FEntityInvPty\": [\r\n            {\r\n                \"FInvPtyId\": {\r\n                    \"FNumber\": \"01\"\r\n                },\r\n                \"FIsEnable\": true,\r\n                \"FIsAffectPrice\": false,\r\n                \"FIsAffectPlan\": false,\r\n                \"FIsAffectCost\": false\r\n            },\r\n            {\r\n                \"FInvPtyId\": {\r\n                    \"FNumber\": \"02\"\r\n                },\r\n                \"FIsEnable\": true,\r\n                \"FIsAffectPrice\": false,\r\n                \"FIsAffectPlan\": false,\r\n                \"FIsAffectCost\": false\r\n            },\r\n            {\r\n                \"FInvPtyId\": {\r\n                    \"FNumber\": \"03\"\r\n                },\r\n                \"FIsEnable\": false,\r\n                \"FIsAffectPrice\": false,\r\n                \"FIsAffectPlan\": false,\r\n                \"FIsAffectCost\": false\r\n            },\r\n            {\r\n                \"FInvPtyId\": {\r\n                    \"FNumber\": \"04\"\r\n                },\r\n                \"FIsEnable\": false,\r\n                \"FIsAffectPrice\": false,\r\n                \"FIsAffectPlan\": false,\r\n                \"FIsAffectCost\": false\r\n            },\r\n            {\r\n                \"FInvPtyId\": {\r\n                    \"FNumber\": \"06\"\r\n                },\r\n                \"FIsEnable\": false,\r\n                \"FIsAffectPrice\": false,\r\n                \"FIsAffectPlan\": false,\r\n                \"FIsAffectCost\": false\r\n            }\r\n        ]\r\n    }\r\n}";
                    var result = client.Save(formId, cs);
                    var resultJObject = JObject.Parse(result);
                    var queryNode = resultJObject.SelectToken("$..IsSuccess");
                    var BONID = resultJObject.SelectToken("$.Result.Id");
                    var BONNmuber = resultJObject.SelectToken("$.Result.Number");
                    if (queryNode != null)
                    {
                        strj = (string)BONNmuber;
                    }
                }
            }
            return strj;
        }
        //取得利润结果
        public string MIoa(string M, string K)
        {
            var JT = M.Split(',');
            var stei = "";
            for (int i = 0; i < JT.Length; i++)
            {
                if (JT[i] != null && JT[i] != "")
                {
                    var jit = JT[i].Split(':');
                    if (jit[0] == K)
                    {
                        stei = jit[1];
                    }
                }
            }
            return stei;
        }

        public ActionResult Bosin(string Name = "", int state = 0)
        {
            if (state == 1)
            {
                try
                {
                    List<Formation> fom = db.Formation.Where(s => s.FM_name.Contains(Name)).ToList();
                    //计算集成
                    //
                    //集成查询客户
                    var client = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Info = new StringBuilder();
                    //业务对象标识
                    string formId = "BD_MATERIAL";
                    string fieldKeys = "FNumber,FName,FSpecification,FErpClsID,FBaseUnitId.FNumber,FRefCost";//名称 编码 规格 采购属性 单位 价格
                    string Filter = "FName like'" + Name + "%'";
                    //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                    var param = new QueryParam()
                    {
                        FormId = formId,
                        FieldKeys = fieldKeys,
                        FilterString = Filter,
                        TopRowCount = 0,
                        StartRow = 0,
                        Limit = 20,
                    };
                    //调用接口
                    var result = client.ExecuteBillQuery(param.ToJson());
                    //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False
                    if (result.Count == 1)
                    {
                        //对返回结果进行解析和校验，这里使用的是JsonPatch
                        var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                        var queryNode = resultJObject.SelectToken("$..IsSuccess");
                        if (queryNode != null)
                        {
                            var isSuccess = queryNode.Value<Boolean>();
                            Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        }
                        else
                        {
                            ApplicationController.Jichewuliao(fom, result);
                            Info.AppendLine("操作成功");
                        }
                    }
                    else
                    {
                        ApplicationController.Jichewuliao(fom, result);
                        Info.AppendLine("操作成功");
                    }
                    var list = from s in fom select new { s.FM_name, s.FM_bai, s.FM_long, s.FM_kuan, s.FM_gao, s.FM_ji, s.FM_Zhuang };
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(list, settings);
                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    string shdunngf = ex.Message;
                    return Json(shdunngf);
                }
            }
            return View();

        }

        private bool ProductSubmit(BOMini mini)
        {
            db.BOMini.Add(mini);
            return true;
        }

        //BOM录入数据库
        [HttpPost]
        public JsonResult AddBoms(List<BOMini> bOMinis)
        {
            //
            char[] letter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            if (bOMinis == null)
            {
                bOMinis = new List<BOMini>();
            }
            var st = 0;
            var hdfu = "";
            for (int i = 0; i < bOMinis.Count; i++)
            {
                if (bOMinis[i].BOM2_chen == "Leve0")
                {
                    var aed = bOMinis[i].BOM2_bian;
                    var vf = bOMinis[i].BOM2_wuLiu;
                    hdfu = bOMinis[i].BOM2_BQing;
                }
                if (bOMinis[i].BOM2_chen == "leve1")
                {
                    bOMinis[i].BOM2_BQing = hdfu + "-" + letter[st].ToString();
                    st++;
                }
                if (bOMinis[i].BOM2_chen == "leve2")
                {
                    if (bOMinis[i - 1].BOM2_chen == "leve1")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing + "-a";
                    }
                    if (bOMinis[i - 1].BOM2_chen == "leve2")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing;
                    }
                }
            }
            foreach (BOMini b in bOMinis)
            {
                int wuliao = (from s in db.Formation where s.FM_name == b.BOM2_wuLiu select s.FM_ID).FirstOrDefault();/*获取formationde id 信息*/
                var appid = db.Formation.Where(s => s.FM_ID == wuliao).FirstOrDefault();/*获取formationde 料号信息*/
                var BOMbia = b.BOM2_bian;
                var app_bom = db.Applications.FirstOrDefault(s => s.AP_bian == BOMbia);
                //进行赋值 添加id的值
                if (wuliao > 0)
                {
                    b.Fo_id = wuliao;
                }
                else
                {
                    b.Fo_id = null;
                }
                var qunji = app_bom.App_BanB;
                b.BOM2_Zhuang = qunji;
                var hunji = b.BOM2_BQing;
                var A = b.BOM2_bian;
                var h = db.BOMini.Where(s => s.BOM2_BQing == hunji && s.BOM2_bian == A && s.BOM2_Zhuang == qunji).FirstOrDefault();///判断该条是否存在
                if (h != null)
                {
                    h.BOM2_wuLiu = b.BOM2_wuLiu;
                    h.BOM2_liao = b.BOM2_liao;
                    h.BOM2_duan = b.BOM2_duan;
                    h.BOM2_Guige = b.BOM2_Guige;
                    h.BOM2_Nian = b.BOM2_Nian;
                    h.BOM2_Yong = b.BOM2_Yong;
                    h.BOM2_fenzi = b.BOM2_fenzi;
                    h.BOM2_Lei = b.BOM2_Lei;
                    h.BOM2_Sone = b.BOM2_Sone;
                    h.BOM2_ST = b.BOM2_ST;
                    db.Entry(h).State = EntityState.Modified;
                }
                else
                {
                    db.BOMini.Add(b);
                }
            }
            int sun = db.SaveChanges();
            return Json(sun);
        }

        //导出Excel文件
        public ActionResult Excelwen(string names)
        {
            //获取数据信息
            var Na_shu = db.Applications.Where(s => s.AP_bian == names).ToList();//申请单信息
            var Na_bom = db.BOMini.Where(s => s.BOM2_bian == names).OrderBy(a => a.BOM2_BQing).ToList();//bom表信息

            return View();
        }

    }
}